<template>
  <el-header height="80px">
    <El_Header />
  </el-header>
  <el-container class="home-container">
    <div class="flight-card" style="margin-top: 60px">
      <div class="flight-info-top">
        <svg width="60" height="60" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg"><g clip-path="url(#icon-1a3702c92fb27154)"><path d="M4.99707 40.9883L42.9971 40.9883" stroke="#ffffff" stroke-width="4" stroke-linecap="round" stroke-linejoin="miter"/><path d="M8.52068 31.2641L3.90765 23.2741C4.87794 22.7139 9.67924 24.3889 11.4666 25.3061L21.1686 21.8332L12.8733 7.46538L16.9879 7.21842L30.3885 19.6798L38.6389 17.0682C42.2926 16.023 43.4449 18.0188 43.675 18.4175C45.0577 20.8123 42.2639 22.4252 41.8648 22.6556C38.672 24.499 8.52068 31.2641 8.52068 31.2641Z" fill="#9b9b9b" stroke="#ffffff" stroke-width="4" stroke-linecap="round" stroke-linejoin="miter"/></g><defs><clipPath id="icon-1a3702c92fb27154"><rect width="48" height="48" fill="#ffffff"/></clipPath></defs></svg>
        <div class="flight-details">
          <div>
            <span class="flight-airline">{{ airline }}</span>
            <span class="flight-date">起飞日期：{{ startDate }}</span>
            <span class="flight-time">{{ duration }}</span>
          </div>
          <div class="flight-route">{{ route }}</div>
        </div>
        <div class="star-container">
          <svg
              v-if="!isCollected"
              @click="toggleCollect"
              width="48"
              height="48"
              viewBox="0 0 48 48"
              fill="none"
              xmlns="http://www.w3.org/2000/svg"
              class="star"
          >
            <path
                d="M23.9986 5L17.8856 17.4776L4 19.4911L14.0589 29.3251L11.6544 43L23.9986 36.4192L36.3454 43L33.9586 29.3251L44 19.4911L30.1913 17.4776L23.9986 5Z"
                fill="none"
                stroke="#ffffff"
                stroke-width="4"
                stroke-linejoin="miter"
            />
          </svg>
          <svg
              v-else
              @click="toggleCollect"
              width="48"
              height="48"
              viewBox="0 0 48 48"
              fill="none"
              xmlns="http://www.w3.org/2000/svg"
              class="star"
          >
            <path
                d="M23.9986 5L17.8856 17.4776L4 19.4911L14.0589 29.3251L11.6544 43L23.9986 36.4192L36.3454 43L33.9586 29.3251L44 19.4911L30.1913 17.4776L23.9986 5Z"
                fill="#ffffff"
                stroke="#ffffff"
                stroke-width="4"
                stroke-linejoin="miter"
            />
          </svg>
        </div>
        <div class="flight-price">
          <span>最低购买价格 ￥{{ price }}</span>
        </div>
      </div>
    </div>
    <div class="flight-card">
      <div class="chart-title">{{ airlineNum }}价格变化趋势</div>
      <div ref="chart" class="chart"></div>
    </div>
  </el-container>
</template>

<script>
import El_Header from "@/components/El_Header.vue";
import * as echarts from 'echarts';
import axios from 'axios';
import dayjs from 'dayjs';

export default {
  name: "Details",
  components: { El_Header },
  data() {
    return {
      airline: '',
      price: '',
      duration: '',
      route: '',
      startDate: '',
      airlineNum: '',
      airlineId: '',
      uid:'',
      isCollected: false, // 增加一个布尔变量来跟踪收藏状态
    };
  },
  computed: {
    formattedStartDate() {
      return dayjs(this.startDate).format('YYYY-MM-DD');
    }
  },
  mounted() {
    this.fetchChartData();
  },
  created() {
    try {
      if (this.$route.query.item) {
        this.item = JSON.parse(this.$route.query.item); // 解析传递过来的 JSON 字符串为对象
        this.airline = this.item.airline; // 设置页面显示需要的数据
        this.price = this.item.price;
        this.duration = this.item.duration;
        this.route = this.item.route;
        this.startDate = this.item.startDate;
        this.airlineNum = this.item.airlineNum;
        this.airlineId = this.item.airlineId;
        this.uid = this.item.uid;
      }
    } catch (error) {
      console.error('Error parsing item data:', error);
    }
  },
  methods: {
    fetchChartData() {
      axios.post('http://localhost:8000/flights/details/predication', { params: { uid: this.uid} })
          .then(response => {
            console.log('Chart data response:', response.data);
            const { dates, prices } = response.data.data;
            console.log('Dates:', dates);
            console.log('Prices:', prices);
            this.initChart(dates, prices);
          })
          .catch(error => {
            console.error('Error fetching chart data:', error);
          });
    },
    initChart(dates, prices) {
      console.log('Initializing chart with data:', dates, prices);
      const chartDom = this.$refs.chart;
      if (!chartDom) {
        console.error('Chart DOM element not found');
        return;
      }
      const myChart = echarts.init(chartDom);
      const option = {
        backgroundColor: '#2D333E',
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: dates,
          axisLine: {
            lineStyle: {
              color: '#fff'
            }
          },
          axisLabel: {
            color: '#fff',
            fontSize: 20,
          }
        },
        yAxis: {
          type: 'value',
          axisLine: {
            lineStyle: {
              color: '#fff'
            }
          },
          axisLabel: {
            color: '#fff',
            fontSize: 20,
          },
          splitLine: {
            lineStyle: {
              color: '#fff',
            }
          }
        },
        series: [
          {
            name: '价格',
            type: 'line',
            stack: 'Total',
            data: prices,
            label: {
              show: true,
              position: 'bottom',
              fontSize: 20,
              color: '#fff',
            }
          }
        ]
      };
      myChart.setOption(option);
    },
    toggleCollect() {
      this.isCollected = !this.isCollected; // 切换收藏状态
      const storedUserId = window.sessionStorage.getItem('userId');
      if(this.isCollected){
        axios.post('http://localhost:8000/users/collect/save', {uid:this.uid, userId: storedUserId}).then(response => {
          if(response.data.status===200){
            console.log(response.data)
            console.log("SAVE OK");
          }
        })
        .catch(error => {
          console.error('Error fetching chart data:', error);
        })
      }else {
        axios.post('http://localhost:8000/users/collect/delete', {uid:this.uid, userId: storedUserId}).then(response => {
          if(response.data.status===200){
            console.log("DELETE OK");
          }
        })
            .catch(error => {
              console.error('Error fetching chart data:', error);
            })
      }
    }
  }
};
</script>

<style scoped lang="less">
.chart {
  width: 100%;
  height: 400px;
}

.el-header {
  background-color: #222831;
  display: flex;
  justify-content: space-between;
  padding-left: 0;
  align-items: center;
  color: #fff;
  font-size: 30px;

  > div {
    display: flex;
    align-items: center;

    span {
      margin-left: 15px;
    }
  }
}

.home-container {
  height: 100%;
  width: 100%;
  background-color: #2D333E;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.flight-card {
  width: 60%;
  background-color: #2D333E;
  color: #fff;
  border-radius: 10px;
  padding: 20px;
  margin: 20px 0;
  border: 3px solid #dbe2ef;
}

.flight-info-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.airline-logo {
  width: 50px;
  height: 50px;
}

.flight-details {
  flex: 1;
  margin-left: 20px;
}

.flight-date, .flight-time, .flight-duration, .flight-route {
  display: block;
  margin-bottom: 4px;
}

.flight-airline {
  display: block;
  font-weight: bolder;
  font-size: 25px;
  margin-bottom: 10px;
}

.flight-price {
  text-align: right;
  font-weight: bolder;
  font-size: 25px;
}

.chart-title {
  color: #dbe2ef;
  text-align: center; /* 居中对齐 */
  font-weight: bolder;
  font-size: 25px;
}

.star-container {
  display: flex;
  justify-content: center;
  margin-right: 30px;
}

.star {
  cursor: pointer;
}
</style>
